/*
 * @Autor: dingxiaolin
 * @Date: 2020-04-16 14:27:09
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2020-04-28 22:55:29
 */
var getRawBody = require('raw-body');
var getFormBody = require('body/form');
const request = require('request-promise')

/*
if you open the initializer feature, please implement the initializer function, as below:
module.exports.initializer = function(context, callback) {
    console.log('initializing');
    callback(null, '');
};
*/
//url转base64编码
// const tranlateImg = () => {
//     var url = 'http://sinostoragedev1.oss-cn-beijing.aliyuncs.com/source/QQ%E6%88%AA%E5%9B%BE20200420095110.png';  //一张网络图片
//     http.get(url, (res) => {
//         var chunks = [];
//         var size = 0;
//         res.on('data', (chunk) => {
//             chunks.push(chunk);
//             size += chunk.length;　　//累加缓冲数据的长度
//         });
//         res.on('end', async (err) => {
//             var data = Buffer.concat(chunks, size);
//             var base64Img = data.toString('base64');
//             search(base64Img);
//         });
//     });
// }
// 识别车牌号
const search = async (base64Data) => {
    console.log('11')
    const AccessToken_options = {
        method: 'POST',
        url: 'https://aip.baidubce.com/oauth/2.0/token',
        qs: {
            grant_type: 'client_credentials',
            client_id: 'jzGnIvW8RIhA2vBQSipBPhZF',
            client_secret: 'vrlLunAxAbrCIuqRVCuMwbaLikhCDFVs',
        },
        json: true
    };
    const resultValue = await request(AccessToken_options);
    console.log('1', resultValue.access_token, base64Data)
    const AccessToken_options2 = {
        method: 'POST',
        url: `https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=` + resultValue.access_token,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        form: {
            image: base64Data
        },
        json: true
    };
    try {
        const resultValue2 = await request(AccessToken_options2)
        console.log('2', resultValue2)
        return resultValue2
    } catch (err) {
        console.log("err", err)
    }
}
module.exports.handler = function (req, resp, context) {
    getFormBody(req, async (err, body) => {
        var base64Data = JSON.parse(JSON.stringify(body)).image;
        console.log('data', base64Data)
        if (base64Data) {
            let data = await search(base64Data);
            console.log('data', data)
            if (data.words_result) {
                await sendResp(data.words_result)
            } else {
                await sendResp({
                    data: "未识别到数据"
                })
            }
        } else {
            await sendResp({
                data: "请输入识别链接"
            })
        }
    });

    // 返回
    sendResp = (data) => {
        resp.setHeader('content-type', 'application/json');
        try {
            resp.send(JSON.stringify({
                success: true,
                data: data
            }));
        }
        catch (err) {
            resp.send(JSON.stringify({
                success: false,
                data: err.message
            }));
        }
    };

    base64_encode = (file) => {
        let bitmap = fs.readFileSync(file);
        return new Buffer(bitmap).toString('base64');
    }
}
